/**
 * 2010(c) www.jCaramel.com
 * LOADER
 * 
 * Shows a loader on an element, and optionally disables it from clicking
 * 
 * Requires
 *  jCaramel-Core
 */

jCaramel.loader = {
	
	/**
	 * Creates the loader
	 * @param {Object} element
	 * @param {Object} settings
	 */
	_create: function(element, settings){
		
		//Create handle
		jCaramel.createHandle(element);
		
		//Create loader
		var loader = jQuery('<div>').addClass('loader loader-' + settings.bg);
		
		//Attach loader
		jQuery('body').append(loader)
		
		//Create handle for loader
		jCaramel.createHandle(loader);
		
		//Add image
		if(settings.image === true){
			var img = jQuery('<div>').addClass('loader-image');
			jCaramel.createHandle(img);
			loader.append( img );
			jCaramel.loader.next(img.tag('handle'), 1);
		}
		
		//Add separator
		loader.append( jQuery('<div>').html('&nbsp;') );
		
		//Add text
		loader.append( jQuery('<div>').addClass('loader-text').html(settings.text) );
		
		//Relate to each other
		element.tag('loader', loader.tag('handle'));
		loader.tag('owner', element.tag('handle'));
		
		//Place loader
		var eoff = element.offset();
		loader.css({top: eoff.top, left:eoff.left})
			.width(element.outerWidth())
			.height(element.outerHeight())
			.css('z-index', 99999999);
	
		
	},
	
	/**
	 * Goes to the next animation frame
	 * @param {Object} handle
	 * @param {Object} index
	 */
	next: function(handle, index){
		
		var div = jCaramel.getByHandle(handle);
		var last = index - 1;
		
		if(index > 15) index = 1;
		if(last < 1) last = 15;
		
		div.removeClass('loader-image-' + last).addClass('loader-image-' + index); 
		
		setTimeout('jCaramel.loader.next(' + handle + ',' + (index + 1) + ')', 50);
	},
	
	/**
	 * Sets the text of the loader
	 * @param {Object} element
	 * @param {Object} text
	 */
	text: function(element, text){
		
	},
	
	/**
	 * 
	 * @param {Object} element
	 */
	remove: function(element){
		
	}
	
};

/**
 * Shows, hides or changes a loader on an element
 * @param {Object} a
 * @param {Object} b
 * @param {Object} c
 */
jQuery.fn.loader = function(a, b, c){

	if (a === false) {
		jCaramel.loader.remove(this);
		return this;
	}else if(typeof(a) == "string"){
		return jCaramel.loader[a](this, b);
	}else {
		settings = jQuery.extend({
		
			/**
			 * Black, White, None
			 */
			bg: 'black',
			
			/**
			 * Show loader image
			 */
			image: true,
			
			/**
			 * String indicating state
			 */
			text: ''
		
		}, a);
		
		//Create the listview
		jCaramel.loader._create(this, settings);
		
		return this;
		
	}
};

 